//
//  YMTestReportChartsView.m
//  YMMedical
//
//  Created by y s on 2023/7/21.
//

#import "YMTestReportChartsView.h"
#import <Charts/Charts-Swift.h>
#import "YMTestReportMarkerView.h"
#import "YMMedicalTools.h"


@interface YMTestReportChartsView ()<ChartViewDelegate,ChartAxisValueFormatter>

/** 图 */
@property (nonatomic, strong) LineChartView *vChart;

/** 提示框 */
@property (nonatomic, strong) YMTestReportMarkerView *vMarker;
@property (nonatomic, strong) ChartMarkerView *markerView;
@property (nonatomic, strong) UILabel *lblUnit;
@property (nonatomic, strong) NSArray *arrX;

@property (nonatomic, strong) NSArray *arrData;

@property (nonatomic, assign) CGFloat markY;



@end

@implementation YMTestReportChartsView

- (instancetype)init{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

#pragma mark -- UI
- (void)setUI{
    UIView *vBg = [[UIView alloc] init];
    vBg.backgroundColor = STheme.D9;
    vBg.clipsToBounds = YES;
    vBg.layer.cornerRadius = [SFitUtil fit:8];
    [self addSubview:vBg];
    [vBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo([SFitUtil fit:15]);
        make.right.mas_equalTo([SFitUtil fit:-15]);
        make.top.bottom.mas_equalTo(0);
    }];
    
    UIView *vCircle = [[UIView alloc] init];
    vCircle.layer.borderWidth = [SFitUtil fit:1.5];
    vCircle.layer.borderColor = STheme.D12.CGColor;
    vCircle.clipsToBounds = YES;
    vCircle.layer.cornerRadius = [SFitUtil fit:6];
    [vBg addSubview:vCircle];
    [vCircle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo([SFitUtil fit:13]);
        make.size.mas_equalTo([SFitUtil fitSize:12 height:12]);
        make.top.mas_equalTo([SFitUtil fit:16]);
    }];
    
    self.lblUnit = [SThemeUtil boldLabel:KLanguage(@"concentration_txt") color:STheme.H_D1 fontSize:14];
    [vBg addSubview:self.lblUnit];
    [self.lblUnit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vCircle.mas_right).offset([SFitUtil fit:4]);
        make.right.mas_equalTo([SFitUtil fit:-15]);
        make.centerY.equalTo(vCircle);
    }];
    
    [vBg addSubview:self.vChart];
    [self.vChart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(vCircle.mas_bottom).offset([SFitUtil fit:5]);
        make.bottom.mas_equalTo([SFitUtil fit:-16]);
    }];
    
}

- (void)setDict:(NSDictionary *)dict{
    _dict = dict;
    NSString *sampleType = [SDataUtil stringOf:dict[@"sampleType"]];
    NSString *resPlotLegendLabel = [SDataUtil stringOf:dict[@"resPlotLegendLabel"] valid:@""];
    if (resPlotLegendLabel != nil && resPlotLegendLabel.length > 0){
        self.lblUnit.text = resPlotLegendLabel;
    }else{
        if ([sampleType isEqualToString:KLanguage(@"niao_24")]){
            self.lblUnit.text = [NSString stringWithFormat:@"%@(%@)",KLanguage(@"total_txt"),[SDataUtil stringOf:dict[@"adjustedUnit"]]];
        }else{
            self.lblUnit.text = [NSString stringWithFormat:@"%@(%@)",KLanguage(@"concentration_txt"),[SDataUtil stringOf:dict[@"adjustedUnit"]]];
        }
    }
    
    NSArray *arrList = [SDataUtil arrayOf:dict[@"healthRecordDetails"]];
    NSString *collectDate = [SDataUtil stringOf:dict[@"collectDate"] valid:@""];
    if (arrList == nil || arrList.count < 1) {
        self.vChart.data = nil;
        return;
    }
    self.arrData = arrList;
    
    CGFloat max = 0;
    CGFloat min = 0;
    for (int i = 0; i < self.arrData.count; i++) {
        NSDictionary *item = [SDataUtil dictOf:self.arrData[i]];
        CGFloat primaryResPlot = [SDataUtil floatOf:item[@"adjustedResPlot"]];
        if (i == 0){
            min = primaryResPlot;
            max = primaryResPlot;
        }else{
            min = primaryResPlot<min ? primaryResPlot:min;
            max = primaryResPlot>max ? primaryResPlot:max;
        }
    }
    max = max*1.02;
    min = min*0.98;
    CGFloat scale = (max-min)/(max+min);
    if (scale < 0.5){
        max = (max+min)*3/4;
        min = (max+min)*1/4;
    }
    self.arrX = [YMMedicalTools getXDateArray:collectDate count:35];
    NSMutableDictionary *dictData = [[NSMutableDictionary alloc] init];

    NSInteger maxCount = 0;
    for (int i = 0; i < self.arrX.count; i++) {
        NSString *dateItem = [SDataUtil stringOf:self.arrX[i]];
        NSMutableArray *arrY = [[NSMutableArray alloc] init];
        for (NSDictionary *item in self.arrData) {
            NSString *collectDate = [SDataUtil stringOf:item[@"collectDate"]];
            if (collectDate != nil && collectDate.length > 10){
                collectDate = [collectDate substringToIndex:10];
                if ([dateItem isEqualToString:collectDate]){
                    [arrY addObject:item];
                }
            }
        }
        maxCount = arrY.count > maxCount ? arrY.count:maxCount;
        [dictData setValue:arrY forKey:dateItem];
    }
    
    NSMutableArray *arrYAll = [[NSMutableArray alloc] init];
    for (int i = 0; i < maxCount; i++) {
        NSMutableArray *arrSub = [[NSMutableArray alloc] init];
        for (NSString *item in self.arrX) {
            NSArray *arrItem = [SDataUtil arrayOf:dictData[item]];
            if (arrItem.count > i){
                [arrSub addObject:[SDataUtil dictOf:arrItem[i]]];
            }else{
                [arrSub addObject:@{}];
            }
        }
        [arrYAll addObject:arrSub];
    }
    
    NSMutableArray *arrSet = [[NSMutableArray alloc] init];
    for (NSArray *arrY in arrYAll) {
        NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
        for (int i = 0; i < arrY.count; i++) {
            NSDictionary *dictY = [SDataUtil dictOf:arrY[i]];
            CGFloat lineY = [SDataUtil floatOf:arrY[i]];
            if (dictY.count > 0){
                lineY = [SDataUtil floatOf:dictY[@"adjustedResPlot"]];
            }else{
                lineY = -1;
            }
            if (lineY >= 0){
                ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:lineY];
                [arrTemp addObject:entry];
            }
        }
        [arrSet addObject:arrTemp];
    }
    
    _markY = (max-min)*0.5+min;
    _vChart.leftAxis.axisMaximum = max;
    _vChart.leftAxis.axisMinimum = min;
    _vChart.xAxis.labelCount = self.arrX.count;
    _vChart.xAxis.axisMinimum = 0;
    _vChart.xAxis.axisMaximum = self.arrX.count;
    
    LineChartData *data = [[LineChartData alloc] init];
    for (int i = 0; i < arrSet.count; i++) {
        NSArray *setSub = [SDataUtil arrayOf:arrSet[i]];
        NSString *lable = [NSString stringWithFormat:@"line_%d",i];
        LineChartDataSet *set = [[LineChartDataSet alloc] initWithEntries:setSub label:lable];
        [set setColor:[ChartColorTemplates colorFromString:@"#831CB5"]];
        set.drawCircleHoleEnabled = YES;
        set.circleHoleRadius = [SFitUtil fit:3.5];
        set.circleHoleColor = [UIColor clearColor];
        set.circleColor = STheme.D12;
        set.circleRadius = [SFitUtil fit:6];
        set.drawFilledEnabled = NO;
        set.lineWidth = [SFitUtil fit:0];
        set.fillAlpha = 1.0f;//透明度

        //点击选中拐点的交互样式
        set.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
        set.highlightColor = STheme.D12;
        set.drawValuesEnabled = NO;
        [data addDataSet:set];
    }
    self.vChart.data = data;
    
}


#pragma mark -- delegate
- (void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight{
    NSInteger entryX = entry.x;
    if (entryX < self.arrX.count) {
        CGFloat entryY = entry.y;
        NSString *dateStr = [SDataUtil stringOf:self.arrX[entryX]];
        NSDictionary *dictY = nil;
        CGFloat min = 0;
        for (NSDictionary *item in self.arrData) {
            NSString *collectDate = [SDataUtil stringOf:item[@"collectDate"]];
            if (collectDate != nil && collectDate.length > 10){
                collectDate = [collectDate substringToIndex:10];
                if ([dateStr isEqualToString:collectDate]){
                    CGFloat primaryResPlot = [SDataUtil floatOf:item[@"adjustedResPlot"]];
                    CGFloat minItem = fabs(primaryResPlot-entryY);
                    if (dictY == nil){
                        dictY = item;
                        min = minItem;
                    }else{
                        if (min > minItem){
                            dictY = item;
                            min = minItem;
                        }
                    }
                }
            }
        }
        self.vMarker.dict = dictY;
        CGFloat y = 0;
        if (entryY <= _markY) {
            y = -self.vMarker.frame.size.height;
        }
        _vChart.drawMarkers = YES;
        self.markerView.chartView = _vChart;
        if (entryX < self.arrX.count*0.5) {
            self.markerView.offset = CGPointMake([SFitUtil fit:5],y);
        }else{
            self.markerView.offset = CGPointMake(-self.vMarker.frame.size.width-[SFitUtil fit:15],y);
        }
        _vChart.marker = self.markerView;
    }
}

- (NSString *)stringForValue:(double)value
                        axis:(ChartAxisBase *)axis{
    NSArray *arrTemp = [self changeXShowText];
    if ((int)value < arrTemp.count){
        NSString *xTitle = [SDataUtil stringOfArray:arrTemp index:(int)(value)];
        if (xTitle.length > 5){
            xTitle = [xTitle substringFromIndex:5];
            return xTitle;
        }
    }
    return @"";
}

- (NSArray *)changeXShowText{
    
    NSString *collectDate = [SDataUtil stringOf:self.dict[@"collectDate"] valid:@""];
    if (collectDate == nil || collectDate.length < 10){
        return @[];
    }
    NSDateFormatter *matter = [[NSDateFormatter alloc] init];
    matter.dateFormat = @"yyyy-MM-dd";
    collectDate = [collectDate stringByReplacingCharactersInRange:NSMakeRange(8, 2) withString:@"01"];
    NSDate *dateNo = [matter dateFromString:collectDate];
    matter.dateFormat = @"yyyy/MM/dd";
    NSString *dateNoStr = [matter stringFromDate:dateNo];
    
    NSInteger index1 = [self.arrX indexOfObject:dateNoStr];
    NSMutableArray *arrText = [[NSMutableArray alloc] initWithArray:self.arrX];
    for (NSInteger i = index1; i >= 0; i--) {
        if (i == index1-5 || i == index1){
            index1 = index1-5;
        }else{
            [arrText replaceObjectAtIndex:i withObject:@""];
        }
    }
    
    NSInteger index2 = [self.arrX indexOfObject:dateNoStr];
    for (NSInteger i = index2+1; i < self.arrX.count; i++) {
        if (i == index2+5){
            index2 = index2+5;
        }else{
            [arrText replaceObjectAtIndex:i withObject:@""];
        }
    }
    return [arrText copy];
}

#pragma mark -- setter and getter
- (LineChartView *)vChart{
    if (_vChart == nil) {
        _vChart = [[LineChartView alloc] init];
        _vChart.backgroundColor = [UIColor clearColor];
        [_vChart setExtraOffsetsWithLeft:[SFitUtil fit:5] top:[SFitUtil fit:5] right:[SFitUtil fit:15] bottom:[SFitUtil fit:10]];
        _vChart.drawBordersEnabled = NO;
        _vChart.drawGridBackgroundEnabled = YES;
        _vChart.gridBackgroundColor = [UIColor clearColor];
        //关闭描述
        _vChart.chartDescription.enabled = NO;
        //关闭图例
        _vChart.legend.enabled = NO;
        //缩放
        _vChart.scaleXEnabled = NO;
        _vChart.scaleYEnabled = NO;
        _vChart.autoScaleMinMaxEnabled = NO;
        _vChart.highlightPerTapEnabled = YES;
        _vChart.highlightPerDragEnabled = YES;
        _vChart.pinchZoomEnabled = NO;  //手势捏合
        _vChart.dragEnabled = YES;
        _vChart.dragDecelerationFrictionCoef = 0.7;  //0 1 惯性
        //代理
        _vChart.delegate = self;
        _vChart.noDataText = KLanguage(@"status_empty");
        _vChart.noDataFont = [SFitUtil fitFont:12];
        _vChart.noDataTextColor = [SUIUtil colorOf:0x6D747E];
        //默认YES
        _vChart.drawMarkers = YES;
        
        self.markerView.chartView = _vChart;
        _vChart.marker = self.markerView;
        //自定义的maskView
        [self.markerView addSubview:self.vMarker];
        
        //leftAxis
        ChartYAxis *leftAxis = _vChart.leftAxis;
        leftAxis.enabled = YES;
        leftAxis.labelPosition = YAxisLabelPositionOutsideChart;
        leftAxis.drawGridLinesEnabled = YES;
        leftAxis.gridLineDashLengths = @[@2,@0];
        leftAxis.gridColor = [SUIUtil colorOf:0xDEE3E9];
        leftAxis.labelTextColor = [SUIUtil colorOf:0x000000 alpha:0.4];
        leftAxis.labelFont = [SFitUtil fitFont:10];
        leftAxis.decimals = 2;
        leftAxis.labelCount = 5;
        leftAxis.forceLabelsEnabled = YES;
        leftAxis.axisLineColor = [SUIUtil colorOf:0xDEE3E9];
        
        //rightAxis
        ChartYAxis *rightAxis = _vChart.rightAxis;
        rightAxis.enabled = NO;
        
        //xAxis
        ChartXAxis *xAxis = _vChart.xAxis;
        xAxis.enabled = YES;
        xAxis.labelPosition = XAxisLabelPositionBottom;
        //不画线
        xAxis.drawGridLinesEnabled = YES;
        xAxis.gridLineDashLengths = @[@2,@0];
        xAxis.gridColor = [SUIUtil colorOf:0xDEE3E9];
        xAxis.labelTextColor = [SUIUtil colorOf:0x000000 alpha:0.4];
        xAxis.labelFont = [SFitUtil fitFont:10];
        xAxis.decimals = 0;
//        xAxis.axisMaximum = 1000;
        xAxis.axisLineColor = [SUIUtil colorOf:0xDEE3E9];
        xAxis.valueFormatter = self;
    }
    return _vChart;
}
- (YMTestReportMarkerView *)vMarker{
    if (_vMarker == nil) {
        _vMarker = [[YMTestReportMarkerView alloc] initWithFrame:CGRectMake([SFitUtil fit:5], 0, [SFitUtil fit:156], [SFitUtil fit:78])];
        _vMarker.layer.cornerRadius = [SFitUtil fit:4];
        _vMarker.backgroundColor = [SUIUtil colorOf:0xffffff];
        _vMarker.layer.shadowColor = [SUIUtil colorOf:0x831CB5 alpha:0.2].CGColor;
        _vMarker.layer.shadowOpacity = 1.0;
        _vMarker.layer.shadowOffset = CGSizeMake(0, 1);
    }
    return _vMarker;
}
- (ChartMarkerView *)markerView{
    if (_markerView == nil) {
        _markerView = [[ChartMarkerView alloc] init];
    }
    return _markerView;
}


@end
